package com.example.pei.ithinklearnt.view.activity;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.model.SkillModel;
import com.example.pei.ithinklearnt.model.SkillModelImp;
import com.example.pei.ithinklearnt.utils.ToastUtil;
import com.example.pei.ithinklearnt.view.fragments.innerfragments.DetailedInformationFragment;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ChooseSkillActivity extends AppCompatActivity {

    private SkillModel skillModel;

    private int type;   //3为我想学  ，8为我会
    private ArrayList<String> selectedSkills;
    private ArrayList<String> hideSkills;

    private KProgressHUD hud; //等待进度条


    LayoutInflater mInflater;

    @BindView(R.id.id_flowlayout)
    TagFlowLayout flowLayout;
    @BindView(R.id.btn_cancel)
    Button buttonCancel;
    @BindView(R.id.btn_confirm)
    Button buttonConfirm;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInflater = LayoutInflater.from(this);
        skillModel=new SkillModelImp();
        setContentView(R.layout.activity_choose_skill);
        ButterKnife.bind(this, this);

        initDate();
    }

    @OnClick(R.id.btn_confirm)
    void Confirm(){
        hud = KProgressHUD.create(ChooseSkillActivity.this)
                .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                .setDimAmount(0.4f)
                .setLabel("正在修改...")
                .setCornerRadius(10)
                .show();
        Set<Integer> selected= flowLayout.getSelectedList();
        ArrayList<String> listSkills=new ArrayList<>();
        //将set转为Arraylist
        for (int s : selected) {
            listSkills.add(flowLayout.getAdapter().getItem(s).toString());
        }
        //将Arraylist转为String[]
        int i=0;
        final String[] stringSkills=new String[listSkills.size()];
        for(String s:listSkills){
            stringSkills[i++]=s;
        }
        final Intent intent=new Intent();
        intent.putStringArrayListExtra("skills",listSkills);


        if(type== DetailedInformationFragment.WEAKMAXNUMBER){  //我想学
            skillModel.updateUserSkill(AppApplication.getCurrentUser(), stringSkills, null,
                    new SkillModelImp.updateUserSkillListener() {
                        @Override
                        public void failed() {
                            ToastUtil.ToastShow(ChooseSkillActivity.this,"修改失败，请检查网络或者稍后再试~",0);
                            hud.dismiss();
                        }
                        @Override
                        public void succeed() {
                            //更新本地的技能
                            skillModel.writeUserWeakSkillsToLocal(AppApplication.getCurrentUser().getUsername(),stringSkills);
                            hud.dismiss();
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    });
        }else if(type==DetailedInformationFragment.STRONGMAXNUMBER){//我会
            skillModel.updateUserSkill(AppApplication.getCurrentUser(), null, stringSkills,
                    new SkillModelImp.updateUserSkillListener() {
                        @Override
                        public void failed() {
                            ToastUtil.ToastShow(ChooseSkillActivity.this,"修改失败，请检查网络或者稍后再试~",0);
                            hud.dismiss();
                        }
                        @Override
                        public void succeed() {
                            //更新本地的技能
                            skillModel.writeUserStrongSkillsToLocal(AppApplication.getCurrentUser().getUsername(),stringSkills);
                            hud.dismiss();
                            setResult(RESULT_OK, intent);
                            finish();
                        }
                    });
        }


    }
    @OnClick(R.id.btn_cancel)
    void Cancel(){
        finish();
    }


    private void initDate(){
        type=getIntent().getIntExtra("type",1);
        selectedSkills=getIntent().getStringArrayListExtra("selectedSkills");
        hideSkills=getIntent().getStringArrayListExtra("hideSkills");
        //先从本地读取，这样可以增加用户体验吧，先看到。没有网络也没事
        final String[] localSkills=skillModel.readAllSkills();
        //设置已选的
        final Set<Integer> selected=new HashSet<>();
        //设置需要隐藏的
        final Set<Integer> hide=new HashSet<>();

        for(int i=0;i<localSkills.length;i++){
            //查找所有的选择技能
            for(String selectedSkill:selectedSkills){
                if(selectedSkill.equals(localSkills[i])){  //选中了这个技能
                    selected.add(i);
                }
            }
            //查找需要隐藏的技能的position
            for(String hideSkill:hideSkills){
                if(hideSkill.equals(localSkills[i])){
                    hide.add(i);
                }
            }
        }


        TagAdapter<String> mAdapter=new TagAdapter<String>(localSkills){
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = (TextView) mInflater.inflate(R.layout.skillslabel,flowLayout, false);
                tv.setText(s);
                if(hide.contains(position)){
                    tv.setTag("hide");   //需要隐藏 ，并不关注"hide"内容是什么
                    tv.setText(s+" 不可选");
                }
                return tv;
            }
        };
        mAdapter.setSelectedList(selected);


        flowLayout.setMaxSelectCount(type);
        flowLayout.setAdapter(mAdapter);

        //再从服务器上重新获得
        skillModel.achieveAllSkills(new SkillModelImp.achieveSkillsListener() {
            @Override
            public void succeed(String[] skills) {
                String[] copy=skills.clone();
                Arrays.sort(localSkills);
                Arrays.sort(copy);
                if (Arrays.equals(localSkills, copy)) {
                    //服务器上和本地上数据一致，不需要更新
                } else {
                    skillModel.allSkillsWriteToLocal(skills);     //更新本地
                    for(int i=0;i<skills.length;i++){
                        //查找所有的选择技能
                        for(String selectedSkill:selectedSkills){
                            if(selectedSkill.equals(skills[i])){  //选中了这个技能
                                selected.add(i);
                            }
                        }
                        //查找需要隐藏的技能的position
                        for(String hideSkill:hideSkills){
                            if(hideSkill.equals(skills[i])){
                                hide.add(i);
                            }
                        }
                    }
                    flowLayout.setAdapter(new TagAdapter<String>(skills) {
                        @Override
                        public View getView(FlowLayout parent, int position, String s) {
                            TextView tv = (TextView) mInflater.inflate(R.layout.skillslabel,flowLayout, false);
                            tv.setText(s);
                            if(hide.contains(position)){
                                tv.setTag("hide");   //需要隐藏 ，并不关注"hide"内容是什么
                                tv.setText(s+" 不可选");
                            }
                            return tv;
                        }
                    });
                }

            }
            @Override
            public void failed() {

            }
        });

    }



}
